<template>
	<view class="pagesdoctorPlusAdd">
		<view class="content" v-if="extraProjectPayList.length>0">
			<block v-for="(item, index) in extraProjectPayList" :key="index">
				<extroSimpleItem :extroObj="item" :index='index' :orderObj="orders" @saveRemark="saveRemark"
					@refresh="refresh" @selectArrEvent="selectArrEvent" >
				</extroSimpleItem>
			</block>
		</view>
		<view class="btn-box" v-if="extroProjectDialogShow && btnPayShow">
			<view class="btn-box_info">共计费用
				<text class="redPrice">
					{{ totalAmount }}
				</text>
				元
			</view>
			<view class="btn-box_right">
				全选
				<u-checkbox-group  v-if="btnPayShow"  @change="handleCheckboxChange" style="margin:0 8rpx;">
					<u-checkbox :checked='allChecked' class="btn-box_checkbox" size="38rpx" iconSize="24rpx"></u-checkbox>
				</u-checkbox-group>
				<u-button type="primary" size="mini" @click="confirmRevocation" v-show="btnPayShow" class="btn-box_btn"
					:class="(applyInstitution && applyInstitution.institutionalPaymentSettings === 1)?'active':''">
					{{ applyInstitution && applyInstitution.institutionalPaymentSettings === 1 ? '确认加做项目' : '付款' }}
				</u-button>
			</view>
			
			

		</view>

		<!-- 加做支付信息确认弹窗 -->
		<u-overlay :show="confirmPayDialogVisible" @click="''" zIndex='100'>
			<view class="confirmPayDialog_wrap" v-if="confirmPayDialogVisible">
				<view class="confirmPayDialog_wrap_content">
					<view class="shareQrShow_wrap_content_title">
						确认付款
					</view>
					<view class="confirmPayDialog_wrap_content_container">
						<view class="boldPriceBox">您确认让<text class="boldPrice "> {{ orders.serviceCenterName }} </text>
							执行如下加做项目吗?共 <text class="boldPrice"> {{ multipleSelection.length }} </text>项,总费用<text
								class="boldPrice"> {{ totalAmount }}
							</text>元
						</view>

						<view v-for="(item, index) in multipleSelection" :key="index">
							<view class="confirmPayDialog_wrap_content_item">{{ index + 1 }}. <text
									class="boldPrice">{{ item.doctorAdviceName }}</text> 项目 ,费用
								<text class="boldPrice">
									{{ item.doctorAdviceCost }} 元</text>
							</view>
						</view>
					</view>
					<view class="btnBox1">
						<view class="btn">
							<u-button @tap="confirmPayDialogVisible=false" type="info" size="mini">关 闭</u-button>
						</view>
						<view class="btn">
							<u-button @tap="confirmPayClick" type="primary" size="mini">确 定</u-button>
						</view>

					</view>
				</view>
			</view>
		</u-overlay>
		<!-- 支付二维码 -->
		<u-overlay :show="payDialogVisible" @click="''" zIndex='100'>
			<view class="shareQrShow_wrap" v-if="payDialogVisible">
				<view class="shareQrShow_wrap_content">
					<view class="Imgcontainer" id="Imgcontainer">
						<view class="shareQrShow_wrap_content_title">
							加做项目费用支付
						</view>
						<view class="shareQrShow_wrap_content_dec">
							￥{{payDetails.orderAmount}}金额(元)
						</view>
						<image :src="qrcodeSrc" mode="aspectFit" class="shareQrShow_wrap_content_image"></image>
		
					</view>
					<view class="btnBox1">
						<view class="btn">
							<u-button @tap="payDialogVisible=false" type="info" size="mini">关 闭</u-button>
						</view>
						
		
					</view>
				</view>
			</view>
		</u-overlay>
	</view>
</template>

<script>
	// 加做项
	import QRCode from 'qrcode'
	import request from '@/utils/request'
	import extroSimpleItem from '@/components/common/extroSimpleItem.vue'
	import {
		mapState
	} from 'vuex'
	export default {
		props: ['orders', 'diagnosisId', 'extroProjectDialogShow', 'btnPayShow', 'applyInstitution'],
		components: {
			extroSimpleItem
		},
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo,
				logInType: state => state.user.logInType, //用户身份 1医生  2个人  普通
			}),

		},
		data() {
			return {
				allChecked:false,
				options: {
					color: {
						light: "#ffffff",
						dark: "#111111"
					}
				},
				confirmPayDialogVisible: false,
				typeMap: {
					1: '特殊染色',
					2: '分子病理',
					3: '免疫组化'
				},
				payStatusList: {
					1: '待付款',
					2: '已付款',
					3: '机构做',
					4: '近期已做',
					5: '拒绝支付'
				},
				payStatusListAddPerson: {
					1: '待付款',
					2: '已付款',
					3: '未付款',
					4: '近期已做',
					5: '拒绝支付'
				},
				extraProjectPayList: [],
				totalPages: 0,
				filterForm: {
					page: 0,
					size: 10
				},
				payDialogVisible:false,
				multipleSelection: [],
				totalAmount: 0.0,
				payDetails: {},
				timer: null,
				qrcodeSrc:'',
			};
		},
		mounted() {
			this.getDiagnosisExtraList()
		},
		methods: {
			// 确认加做 
			async confirmRevocation() {
				const res = await request({
					method: 'GET',
					url: `/diagnosis/extra-project/withdrawal/info`,
					params: {
						consultationId: this.extraProjectPayList[0]
							.consultationId //this.multipleSelection[0].consultationId
					}
				})
				if (res.code === 200) {
					if (res.data) {
						this.$modal.showToast('报告已被撤回，暂时无法付款或确认加做项目!请返回重新进入该页面')
					} else {
						this.payClick()
					}
				}

			},
			async payClick() {
				if (this.multipleSelection.length === 0) {
					this.$modal.showToast('请选择加做项目信息，再支付！')
					return
				}
				if (this.logInType == 2) {
					const selectLength = this.extraProjectPayList.filter(item => {
						return item.status === 0 && item.payStatus !== '近期已做'&& item.payStatus !== '拒绝支付'
					}) //医生要求要么加做项目全选要么全不选
					console.log(selectLength)
					if (this.multipleSelection.length < selectLength.length && this.orders
						.allowedUpdateExtraProjects === 0) { //跟着下单的时候设置
						this.$modal.showToast('加做项目未全选！')
						return
					}

					this.confirmPayDialogVisible = true
				} else {
					if (this.applyInstitution.institutionalPaymentSettings === 1) {
						//机构服务设置里不需要网上支付
						this.noPayFun()
					} else {
						this.confirmPayDialogVisible = true

					}
				}

			},
			confirmPayClick() {
				this.confirmPayDialogVisible = false
				if (this.logInType == 2) {
					this.extraOrderWxPay()
					this.payDialogVisible = true
				} else {
					if (this.applyInstitution.institutionalPaymentSettings === 1) {
						//机构服务设置里不需要网上支付
						this.noPayFun()
					} else if (this.applyInstitution.institutionalPaymentSettings === 2) {
						//机构服务设置里需要网上支付

						this.extraOrderWxPay()
						
					}
				}
			},
			async noPayFun() {
				const that = this
				const mData = {
					ordersNumber: that.orders.serialNumber,
					extraProjectsIds: that.multipleSelection.map(n => n.id),
					institutionId: that.orders.serviceCenterId
				}
				const res = await request({
					method: 'POST',
					url: `/orders/create/order/extra`,
					data: mData
				})
				if (res.code === 200) {
					this.refreshDATA()
					this.$emit('refresh')
					this.$modal.showToast('会诊机构设置了无需网上支付,已自动进入下一流程')
				}
			},
			
			async extraOrderWxPay() {
				const that = this
				const mData = {
					body: '爱可及医疗商品', //商品说明：默认“爱可及医疗商品”
					ordersNumber: this.orders.serialNumber, //订单编号
					extraProjectsIds: this.multipleSelection.map(n => n.id),
					institutionId: that.orders.serviceCenterId
				}
				const res = await request({
					method: 'POST',
					url: `/wx/pay/create/order/extra`,
					data: mData
				})

				const _totalOrderAmount = this.multipleSelection.reduce(
					(total, n) => total + (n.doctorAdviceCost || 0) * 100,
					0
				)
				if (res.code === 200) {
					this.payDetails = {
						status: false,
						orderAmount: (_totalOrderAmount / 100).toFixed(2),
						...res.data
					}
					this.createQRCode()//生成支付二维码
					this.timer = setInterval(() => {

						this.wxQueryPay()
					}, 2000)
				}
			},
			//分享二维码
			createQRCode() {
				let pathUrl = this.payDetails.codeUrl
				QRCode.toDataURL(pathUrl, this.options)
					.then(url => {
						this.qrcodeSrc = url
						console.log(url)
						this.payDialogVisible = true
					})
					.catch(err => {
						console.error(err)
					})
			},
			async wxQueryPay() {
				const that = this
				const institutionId = that.orders.serviceCenterId
				const res = await request({
					method: 'GET',
					url: `/wx/pay/query`,
					params: {
						pOrdersDetailNo: this.payDetails.orderDetailNo,
						institutionId: institutionId,
						extraProjectsIds: this.multipleSelection.map(n => n.id).join()
					}
				})
				if (res.code === 200) {
					if (res.data.returnCode == 'SUCCESS') {
						this.payDetails.status = true
						//如果有没选的 那就是申请机构可以自己做的 把没选的改一下状态
						if (this.extraProjectPayList.length != this.multipleSelection.length) {
							const filterHavePayArry = this.extraProjectPayList.filter(
								item => item.payStatus != '已付款'
							)
							const a = filterHavePayArry.map(n => n.id)
							const b = this.multipleSelection.map(n => n.id)
							this.extroProjectNoCheck(a, b)
						}
						this.payDialogClose()
						this.refreshDATA()
						this.$emit('refresh')
					}
				}
			},
			async extroProjectNoCheck(a, b) {
				const arr = [...a, ...b]
				const ids = arr.filter(item => {
					return !(a.includes(item) && b.includes(item))
				})
				const res = await request({
					method: 'POST',
					url: `/diagnosis/extra-project/updatePayStatus`,
					data: JSON.stringify(ids)
				})
			},
			payDialogClose() {
				this.payDialogVisible = false
				clearInterval(this.timer)
			},
			handleCheckboxChange(){
				if(this.allChecked){
					this.allChecked=false
					this.extraProjectPayList =this.extraProjectPayList.map(n => ({
							...n,
							checked: false,
						}))
				}else{
					this.allChecked=true
					this.extraProjectPayList =this.extraProjectPayList.map(n =>{
						if(n.payStatus === '待付款'){
							return{
								...n,
								checked: true,
							}
						}else{
							return{
								...n,
								checked: false,
							}
						}
					})
				}
				this.multipleSelection=[]
				if(this.allChecked){
					this.extraProjectPayList.forEach(n=>{
						if(n.payStatus === '待付款'){
							this.multipleSelection.push(n)
						}
					})
				}
				this.handleSelectionChange()
				
			},
			selectArrEvent(data) {
				if (data.checked) { //选中
					this.multipleSelection.push(data)
				} else { // 删除
					const index = this.multipleSelection.findIndex(item => item.id === data.id);
					this.multipleSelection.splice(index, 1)

				}
				//全选判断
				const selectLength = this.extraProjectPayList.filter(item => {
					return item.status === 0 && item.payStatus !== '近期已做'&& item.payStatus !== '拒绝支付'
				}) 
				if (this.multipleSelection.length < selectLength.length ) { 
					this.allChecked=false
				}else{
					this.allChecked=true
				}
				this.handleSelectionChange()
			},
			handleSelectionChange() {
				this.totalAmount = (
					this.multipleSelection.reduce((total, n) => total + (n.doctorAdviceCost || 0) * 100, 0) /
					100
				).toFixed(2)
			},
			refreshDATA() {
				this.getDiagnosisExtraList()
			},
			// 获取 加做项目单项
			getDiagnosisExtraList() {
				const that = this
				request({
					method: 'GET',
					url: `/diagnosis/extra-project/${that.orders.patients[0].id}`
				}).then(res => {
					if (res && res.code === 200) {
						let data = res.data
						that.extraProjectPayList =
							data.map(n => ({
								...n,
								checked: false,
								statusName: (n.resultUrl || n.result) ? '已上传' : (n.pdfUrl && JSON.parse(n
										.pdfUrl)
									.length > 0) ? '已上传' : '未上传',
								payStatus: that.orders.orderType === 1 ? that.payStatusList[n.payStatus] :
									that.payStatusListAddPerson[n.payStatus],
								typeName: that.typeMap[n.type]
							})).filter(n => n.consultationId == that.diagnosisId) || []
						this.$emit('addPlus', that.extraProjectPayList)
						

					}
				})
			},
			//备注保存
			saveRemark(row) {
				let _this = this
				request({
					method: 'put',
					url: '/diagnosis/extra-project',
					data: {
						id: row.id,
						result: row.result
					}
				}).then(
					res => {
						if (res.code === 200) {
							this.$modal.showToast('保存成功')
							//获取加做项目列表
							this.getDiagnosisExtraList()

						}
					},
					err => {
						this.$modal.showToast(`${err.response.data}`)
					}
				)
			},
			refresh() {
				this.getDiagnosisExtraList()
			}



		}
	}
</script>

<style lang="scss" scoped>
	.btnBox1 {
		display: flex;
		justify-content: space-evenly;
		margin: 20rpx 0;
		// .btn{
		// 	width:100rpx;
		// }
		::v-deep .u-button {
			flex-shrink: 0;
			margin: 10rpx !important;
			// display: block;
			// justify-content: flex-end!important;
		}
	}
	.shareQrShow,.confirmPayDialog {
		&_wrap {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100%;

			&_content {
				width: 90%;
				max-height: 80vh;
				border-radius: 12rpx;
				background: #fff;
				padding:24rpx;

				&_item {
					font-size: 26rpx;
					line-height: 32rpx;
				}
				&_image {
					width: 200rpx;
					height: 200rpx;
					display: block;
					margin: 48rpx auto;
					border: 4rpx solid #3770F6;
				}
				
				&_title {
					font-size: 28rpx;
					line-height: 38rpx;
					font-weight: 700;
					margin-bottom:24rpx;
					text-align: center;
				}
				
				&_dec {
					margin-top: 16rpx;
					font-size: 24rpx;
					line-height: 30rpx;
					text-align: center;
					color: #666;
				}
			}
		}

		
	}

	.btn-box {
		padding: 16rpx 0;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		&_info {
			line-height: 40rpx;
		}
		
		&_right{
			display: flex;
			align-items: center;
		}
		&_checkbox{
			margin-right: 20rpx;
		}

		&_btn {
			width: 100rpx;
			margin: 0rpx
		}

		&_btn.active {
			width: 200rpx;
			margin: 0rpx
		}
	}

	.redPrice {
		color: red;
		font-weight: bold;
	}

	.boldPrice {
		font-weight: bold;
	}

	.boldPriceBox {
		font-size: 26rpx;
		line-height: 32rpx;
		padding-bottom: 12rpx;
	}
</style>